<template>
  <div class="virtual-list" ref="virtualListRef" @scroll="handleScroll">
    <div v-if="!showScrollBar" :style="{ height: items.length * size + 'px' }"></div>
    <div class="container" ref="container" :style="{ top: offsetTop }">
      <div
        v-for="(v, i) in itemList"
        :key="i"
        class="item"
        :style="{ height: size + 'px' }"
      >
        <slot :index="i" :data="v"/>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, onMounted, computed } from 'vue';
export default {
  props: {
    size: { type: Number },
    remain: { type: Number },
    items: { type: Array },
    showScrollBar: {type: Boolean, default: true}
  },
  setup(props) {
    const virtualListRef = ref(null);
    const start = ref(0);
    const offsetTop = ref(0);
    const end = ref(props.remain);
    const itemList = computed(()=>{
      return props.items.slice(start.value, end.value + 3);
    })
    onMounted(()=>{
        virtualListRef.value.style.height = props.size * props.remain + "px";
    })
    const handleScroll = function() {
        //从第几个item开始显示
      start.value = virtualListRef.value.scrollTop / props.size;
        //开始位置加上要显示几个 = end
      end.value = start.value + props.remain;
        //动态更改定位的top值，保证不会随父元素一起滚动
      offsetTop.value = virtualListRef.value.scrollTop + "px";
    }
    console.log(itemList);
    return {
      start,
      end,
      offsetTop,
      handleScroll,
      virtualListRef,
      itemList
    }
  },
};
</script>
<style>
.virtual-list {
  overflow: auto;
  width: 200px;
  position: relative;
}
.container {
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
}
</style>